import React, { createContext, useContext, useReducer, useEffect, useCallback, useMemo, ReactNode } from 'react';

// MCP状态类型定义
interface MCPState {
  isEnabled: boolean;
  isInitialized: boolean;
  isConnecting: boolean;
  error: string | null;
  tools: Map<string, any>;
  agentsStatus: Map<string, { enabled: boolean; toolsCount: number; tools?: string[]; label?: string; error?: string }>;
}

// MCP动作类型
type MCPAction = 
  | { type: 'SET_CONNECTING'; payload: boolean }
  | { type: 'SET_INITIALIZED'; payload: boolean }
  | { type: 'SET_ERROR'; payload: string | null }
  | { type: 'SET_TOOLS'; payload: Map<string, any> }
  | { type: 'SET_AGENT_STATUS'; payload: { agentId: string; status: { enabled: boolean; toolsCount: number; tools?: string[]; label?: string; error?: string } } }
  | { type: 'RESET_STATE' };

// 初始状态
const initialState: MCPState = {
  isEnabled: false,
  isInitialized: false,
  isConnecting: false,
  error: null,
  tools: new Map(),
  agentsStatus: new Map(),
};

// Reducer函数
function mcpReducer(state: MCPState, action: MCPAction): MCPState {
  switch (action.type) {
    case 'SET_CONNECTING':
      return { ...state, isConnecting: action.payload, error: action.payload ? null : state.error };
    case 'SET_INITIALIZED':
      return { ...state, isInitialized: action.payload, isConnecting: false };
    case 'SET_ERROR':
      return { ...state, error: action.payload, isConnecting: false };
    case 'SET_TOOLS':
      return { ...state, tools: action.payload };
    case 'SET_AGENT_STATUS':
      const newAgentsStatus = new Map(state.agentsStatus);
      const normalizedStatus = {
        ...action.payload.status,
        toolsCount: action.payload.status.toolsCount ?? (action.payload.status.tools?.length ?? 0)
      };
      newAgentsStatus.set(action.payload.agentId, normalizedStatus);
      return { ...state, agentsStatus: newAgentsStatus };
    case 'RESET_STATE':
      return initialState;
    default:
      return state;
  }
}

// Context类型
interface MCPContextType {
  state: MCPState;
  dispatch: React.Dispatch<MCPAction>;
  // 便捷方法
  setConnecting: (connecting: boolean) => void;
  setInitialized: (initialized: boolean) => void;
  setError: (error: string | null) => void;
  setTools: (tools: Map<string, any>) => void;
  setAgentStatus: (agentId: string, status: { enabled: boolean; toolsCount: number; tools?: string[]; label?: string; error?: string }) => void;
  resetState: () => void;
  // 计算属性
  getTotalToolsCount: () => number;
  getEnabledAgentsCount: () => number;
  getTotalAgentsCount: () => number;
}

// 创建Context
const MCPContext = createContext<MCPContextType | undefined>(undefined);

// Provider组件
interface MCPProviderProps {
  children: ReactNode;
}

export function MCPProvider({ children }: MCPProviderProps) {
  const [state, dispatch] = useReducer(mcpReducer, initialState);

  // 便捷方法
  const setConnecting = useCallback((connecting: boolean) => {
    dispatch({ type: 'SET_CONNECTING', payload: connecting });
  }, []);

  const setInitialized = useCallback((initialized: boolean) => {
    dispatch({ type: 'SET_INITIALIZED', payload: initialized });
  }, []);

  const setError = useCallback((error: string | null) => {
    dispatch({ type: 'SET_ERROR', payload: error });
  }, []);

  const setTools = useCallback((tools: Map<string, any>) => {
    dispatch({ type: 'SET_TOOLS', payload: tools });
  }, []);

  const setAgentStatus = useCallback((agentId: string, status: { enabled: boolean; toolsCount: number; tools?: string[]; label?: string; error?: string }) => {
    dispatch({ type: 'SET_AGENT_STATUS', payload: { agentId, status } });
  }, []);

  const resetState = useCallback(() => {
    dispatch({ type: 'RESET_STATE' });
  }, []);

  // 计算属性
  const getTotalToolsCount = () => {
    return Array.from(state.agentsStatus.values()).reduce((sum, status) => {
      const count = status.toolsCount ?? (status.tools?.length ?? 0);
      return sum + count;
    }, 0);
  };

  const getEnabledAgentsCount = () => {
    return Array.from(state.agentsStatus.values()).filter(status => status.enabled).length;
  };

  const getTotalAgentsCount = () => {
    return state.agentsStatus.size;
  };

  const contextValue = useMemo<MCPContextType>(() => ({
    state,
    dispatch,
    setConnecting,
    setInitialized,
    setError,
    setTools,
    setAgentStatus,
    resetState,
    getTotalToolsCount,
    getEnabledAgentsCount,
    getTotalAgentsCount,
  }), [state, dispatch, setConnecting, setInitialized, setError, setTools, setAgentStatus, resetState]);

  return (
    <MCPContext.Provider value={contextValue}>
      {children}
    </MCPContext.Provider>
  );
}

// Hook
export function useMCP() {
  const context = useContext(MCPContext);
  if (context === undefined) {
    throw new Error('useMCP must be used within a MCPProvider');
  }
  return context;
}

// 便捷Hook
export function useMCPStatus() {
  const { state, getTotalToolsCount, getEnabledAgentsCount, getTotalAgentsCount } = useMCP();
  
  return {
    ...state,
    totalToolsCount: getTotalToolsCount(),
    enabledAgentsCount: getEnabledAgentsCount(),
    totalAgentsCount: getTotalAgentsCount(),
  };
}
